package com.ch.forum.service.impl;

import com.ch.forum.bo.PageResult;
import com.ch.forum.bo.ReplyListVo;
import com.ch.forum.bo.ReplyVo;
import com.ch.forum.bo.ResponseResult;
import com.ch.forum.dao.ReplyMapper;
import com.ch.forum.model.ReplyModel;
import com.ch.forum.model.UserModel;
import com.ch.forum.service.ReplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ReplyServiceImpl implements ReplyService {

    @Autowired
    private ReplyMapper replyMapper;

    @Override
    public ResponseResult addReply(ReplyVo vo) {

        int num = 0;
        int count = 0;
        if(vo.getReRelpyId() != null){
            num = replyMapper.findReplyNumById(vo.getReRelpyId());
            count = replyMapper.updateReplyNum(num + 1);
        }

        ReplyModel model = new ReplyModel();
        model.setArtId(vo.getArtId());
        model.setContent(vo.getContent());
        model.setDate(new Date(System.currentTimeMillis()));
        model.setIsPre(vo.getIsPre());
        model.setReUserId(vo.getReUserId() != null ? vo.getReUserId() : null);
        model.setUserId(vo.getUserId());
        model.setZanNum(0);
        model.setReReplyNum(0);
        Long id = replyMapper.addReply(model);

        return new ResponseResult(true,"成功");
    }

    @Override
    public ResponseResult findReplyPageByArtId(Long artId, int pageNo, int pageSize) {
        int pageNum = (pageNo - 1)*pageSize;
        List<ReplyListVo> records = replyMapper.findReplyPageByArtId(artId, pageNum, pageSize);
        int totalRecords = replyMapper.countReplyByArtId(artId);
        return new ResponseResult(true, "",
                new PageResult(pageNo, pageSize, totalRecords, records));
    }

    @Override
    public ResponseResult findMyReplyByUserId(Long userId, int pageNo, int pageSize) {
        int pageNum = (pageNo - 1)*pageSize;
        List<ReplyListVo> records = replyMapper.findMyReplyByUserId(userId, pageNum, pageSize);
        int totalRecords = replyMapper.countMyReplyByUserId(userId);
        return new ResponseResult(true, "",
                new PageResult(pageNo, pageSize, totalRecords, records));
    }

    @Override
    public void sendPreReply(int num) {
        List<Long> ids = replyMapper.findPreReplyIds();
        StringBuilder sb = new StringBuilder();
        if(ids != null && ids.size() > 0){
            if(num <= ids.size()){
                for(int i = 0; i<num; i++){
                    sb.append(ids.get(i)).append(",");
                }
            }

            if(num > ids.size()){
                for(int i = 0; i<ids.size(); i++){
                    sb.append(ids.get(i)).append(",");
                }
            }

            replyMapper.updateIsPre(sb.toString().substring(0, sb.toString().length() -1));
        }
    }


}
